package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"sync"
	"time"
)

// 定义一个函数，用于下载URL的内容
func fetchURL(url string, wg *sync.WaitGroup) {
	defer wg.Done() // 任务完成时通知WaitGroup

	start := time.Now()
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("Error fetching %s: %v\n", url, err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body from %s: %v\n", url, err)
		return
	}

	// 打印下载结果
	fmt.Printf("Fetched %s, length: %d, time: %v\n", url, len(body), time.Since(start))
}

func main() {
	// 定义要下载的URL列表
	urls := []string{
		"https://www.example.com",
		"https://www.google.com",
		"https://www.github.com",
		"https://www.stackoverflow.com",
	}

	var wg sync.WaitGroup // 创建一个WaitGroup

	// 遍历URL列表，为每个URL启动一个Goroutine
	for _, url := range urls {
		wg.Add(1) // 每启动一个Goroutine，WaitGroup计数器加1
		go fetchURL(url, &wg)
	}

	// 等待所有Goroutine完成
	wg.Wait()
	fmt.Println("All downloads completed!")
}
